package com.znsd.zl.redis.config;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName RedisConfig
 * @Description 自定义Redis配置类
 * @Author jaypdd
 * @Date 2020/8/12 20:45
 * @Version v1.0
 */
@Configuration
public class RedisConfig {

	@Bean
	public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		//设置Key序列化要使用的模板，默认是JdkSerializationRedisSerializer
		redisTemplate.setKeySerializer(stringSerializer());
		//设置value序列化要使用的模板，默认是JdkSerializationRedisSerializer
		redisTemplate.setValueSerializer(jacksonSerializer());
		//设置次莫版要使用的哈希key(或field)序列化程序，默认是JdkSerializationRedisSerializer
		redisTemplate.setHashKeySerializer(stringSerializer());
		//设置此模板要使用的哈希值序列化程序，默认是JdkSerializationRedisSerializer
		redisTemplate.setHashValueSerializer(jacksonSerializer());
		return redisTemplate;
	}

	/**
	 * 初始化string序列化对象
	 * @return
	 */
	@Bean
	public RedisSerializer stringSerializer() {
		return new StringRedisSerializer();
	}

	/**
	 * 初始化jackson序列化对象
	 */
	@Bean
	public RedisSerializer jacksonSerializer() {
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
		ObjectMapper objectMapper = new ObjectMapper();
		//更改自动检测的属性类
		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
		return jackson2JsonRedisSerializer;
	}

}
